package com.ego.service.impl;

import com.ego.commons.constant.Constant;
import com.ego.commons.pojo.CartPojo;
import com.ego.commons.pojo.EgoResult;
import com.ego.commons.pojo.ShopCart;
import com.ego.commons.utils.JsonUtils;
import com.ego.commons.utils.ServletUtil;
import com.ego.dubbo.service.TbItemDubboService;
import com.ego.pojo.TbItem;
import com.ego.pojo.TbItemDetails;
import com.ego.pojo.TbUser;
import com.ego.service.CartService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title
 * @Author Lyg
 * @Description:
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${ego.item.detailRedisKey}")
    private String redisDetialKey;
    @DubboReference
private TbItemDubboService itemDubboService;

    @Override
    public void cartAdd(Long id, int num) {
        //从Redis中获取缓存的商品详情数据
//        TbItemDetails tbItemDetail = (TbItemDetails)redisTemplate.opsForValue().get(redisDetialKey + id);
        TbItem tbItem = itemDubboService.selectById(id);
        TbItemDetails tbItemDetail = new TbItemDetails();
        BeanUtils.copyProperties(tbItem,tbItemDetail);
        tbItemDetail.setImages(tbItem.getImage().split(","));


        //1.创建购物车对象 CartPojo 封装数据
        CartPojo cartPojo = new CartPojo();
        //将TbItemDetail设置给CartPojo
        //如果上面拷贝num是商品库存数量，需要重新设置CartPojo的num为用户购买的数量
        BeanUtils.copyProperties(tbItemDetail,cartPojo);
        cartPojo.setNum(num);
        //获取购物车
        ShopCart shopCart = this.getShopCart();
        //添加数据到购物车
        shopCart.addToCart(cartPojo);
        //存储购物车
        this.saveCartToCookieOrRedis(shopCart);

    }

    @Override
    public List<CartPojo> cartList() {
        //获取购物车
        ShopCart shopCart = this.getShopCart();
        List<CartPojo> cartList = shopCart.getCartList();
        return cartList;
    }

    @Override
    public EgoResult deleteCartItemByItemId(Long id) {
        try {
            ShopCart shopCart = this.getShopCart();
            //删除购物车数据
            shopCart.deleteToCart(id);
            //保存购物车
            this.saveCartToCookieOrRedis(shopCart);
            return EgoResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EgoResult.error("删除购物车数据失败");
        }
    }

    @Override
    public EgoResult updateCartItemNum(long id, int num) {
        try {
            ShopCart shopCart = this.getShopCart();
            shopCart.updateToCart(id,num);
            ShopCart.saveCartToCookie(shopCart);
            return EgoResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EgoResult.error("修改购物车数据失败");
        }
    }

    @Override
    public List<CartPojo> orderCartByIds(List<Long> ids) {
        ShopCart shopCart = this.getShopCart();
        List<CartPojo> cartPojos=new ArrayList<>();
        List<CartPojo> cartList = shopCart.getCartList();
        for (CartPojo cartPojo : cartList) {

            //如果用户结算的商品id在购物车中有对应的商品对象，才会添加到结算集合中：orderList
            if (ids.contains(cartPojo.getId())){
                //从缓存中获取商品详情，获取商品库存数量
                TbItemDetails tbItemDetail = (TbItemDetails) redisTemplate.opsForValue().get(redisDetialKey + cartPojo.getId());
                //获取商品详情库存数量
                Integer storageNum = tbItemDetail.getNum();
                //获取购买数量
                Integer buyNum = cartPojo.getNum();

                //如果库存数量大于等于购买数量说明库存足够，可以购买
                if(storageNum>=buyNum){
                    cartPojo.setEnough(true);
                }
                cartPojos.add(cartPojo);
            }
        }

        return cartPojos;
    }

    /**
     * 存储购物车，如果未登录：存储到Cookie，如果登录：存储到Redis
     * @param shopCart
     */
    public void saveCartToCookieOrRedis(ShopCart shopCart){
        HttpSession session = ServletUtil.getRequest().getSession();

        TbUser loginUser = (TbUser) session.getAttribute(Constant.LOGIN_USER_IN_SESSION);

        if (loginUser!=null){
            redisTemplate.opsForValue().set(Constant.LOGIN_USER_REDIS_SHOP_CART_KEY_PREFIX+loginUser.getUsername(), shopCart);
        }else {
            ShopCart.saveCartToCookie(shopCart);
        }

    }

    /**
     * 封装获取购物车数据
     * @return
     */
    public ShopCart getShopCart(){
        HttpSession session = ServletUtil.getRequest().getSession();
        //获取登录用户的Session中的信息
        TbUser loginUser = (TbUser) session.getAttribute(Constant.LOGIN_USER_IN_SESSION);
        ShopCart shopCart=null;

        System.out.println("loginUser = " + loginUser);
        if (loginUser!=null){
            shopCart= (ShopCart)redisTemplate.opsForValue().get(Constant.LOGIN_USER_REDIS_SHOP_CART_KEY_PREFIX+loginUser.getUsername());

            if (shopCart==null){
                shopCart=new ShopCart();
            }
        }else {
            shopCart= ShopCart.getShopCartByCookie();
        }

        return shopCart;
    }
}
